<template>
  <div class="teacher-page">
    <header>
      <el-form-item label="教师姓名:" label-width="80px" class="label-right-align">
        <el-input v-model="queryData.TCHR_NAME" type="text" clearable></el-input>
      </el-form-item>

      <el-button @click.prevent="loadTeachers">
        <el-icon><Search /></el-icon>
        <span>查询</span>
      </el-button>

      <el-button @click.prevent="handleAdd">
        <el-icon><DocumentAdd /></el-icon>
        <span>增加</span>
      </el-button>

      <el-button @click.prevent="handleBatchDelete">
        <el-icon><Delete /></el-icon>
        <span>批量删除</span>
      </el-button>
    </header>

    <el-table 
      ref="tableRef"
      :data="teachers" 
      v-loading="loading" 
      border 
      style="width: 100%"
      stripe
      @sort-change="handleSort"
      :height="tableHeight"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="TCHR_UUID" :label="$t('teacher.id')" width="280" />
      <el-table-column prop="TCHR_NAME" :label="$t('teacher.name')" width="120" sortable="custom" />
      <el-table-column prop="EMAIL" :label="$t('teacher.email')" width="180" sortable="custom" />
      <el-table-column prop="TCHR_LEVEL" :label="$t('teacher.levelLabel')" width="120">
        <template #default="{ row }">
          <el-tag :type="getTeacherLevelType(row.TCHR_LEVEL)">
            {{ getTeacherLevelLabel(row.TCHR_LEVEL) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="INTRODUCTION" :label="$t('teacher.introduction')" />
      <el-table-column :label="$t('common.actions')" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleEdit(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button link type="danger" size="small" @click="handleDelete(row)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      layout="total,sizes,->,prev,pager,next,jumper"
      :total="total"
      :page-size="queryData.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="queryData.currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- Teacher Form Dialog -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item :label="$t('teacher.name')" prop="TCHR_NAME">
          <el-input v-model="form.TCHR_NAME" />
        </el-form-item>
        <el-form-item :label="$t('teacher.email')" prop="EMAIL">
          <el-input v-model="form.EMAIL" />
        </el-form-item>
        <el-form-item :label="$t('teacher.levelLabel')" prop="TCHR_LEVEL">
          <el-select v-model="form.TCHR_LEVEL" style="width: 100%">
            <el-option :label="$t('teacher.level.junior')" :value="1" />
            <el-option :label="$t('teacher.level.mid')" :value="2" />
            <el-option :label="$t('teacher.level.senior')" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('teacher.avatar')" prop="TCHR_PHONE_URL">
          <el-input v-model="form.TCHR_PHONE_URL" />
        </el-form-item>
        <el-form-item :label="$t('teacher.introduction')" prop="INTRODUCTION">
          <el-input
            v-model="form.INTRODUCTION"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleSubmit">
          {{ $t('common.confirm') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import axios from 'axios'
import $ from 'jquery'

const { t } = useI18n()

// Data
const loading = ref(false)
const teachers = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const tableRef = ref()
const tableHeight = ref(600)
const total = ref(0)

const queryData = ref({
  currentPage: 1,
  pageSize: 10,
  sortField: '',
  sortOrder: 'asc',
  TCHR_NAME: ''
})

const form = ref({
  TCHR_UUID: '',
  TCHR_NAME: '',
  EMAIL: '',
  TCHR_LEVEL: 1,
  TCHR_PHONE_URL: '',
  INTRODUCTION: ''
})

const rules: FormRules = {
  TCHR_NAME: [
    { required: true, message: t('teacher.nameRequired'), trigger: 'blur' },
    { min: 2, max: 100, message: t('teacher.nameLength'), trigger: 'blur' }
  ],
  EMAIL: [
    { required: true, message: t('teacher.emailRequired'), trigger: 'blur' },
    { type: 'email', message: t('teacher.emailFormat'), trigger: 'blur' }
  ],
  TCHR_LEVEL: [
    { required: true, message: t('teacher.levelRequired'), trigger: 'change' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? t('teacher.edit') : t('teacher.add')
})

// Methods
const loadTeachers = async () => {
  loading.value = true
  try {
    const response = await axios.post('/api/teachers/query', queryData.value)
    if (response.data) {
      teachers.value = response.data.list || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    ElMessage.error(t('common.loadError'))
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  isEdit.value = false
  form.value = {
    TCHR_UUID: '',
    TCHR_NAME: '',
    EMAIL: '',
    TCHR_LEVEL: 1,
    TCHR_PHONE_URL: '',
    INTRODUCTION: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(t('common.deleteConfirm'), t('common.warning'), {
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/teachers/${row.TCHR_UUID}`)
      ElMessage.success(t('common.deleteSuccess'))
      loadTeachers()
    } catch (error) {
      ElMessage.error(t('common.deleteError'))
    }
  })
}

const handleBatchDelete = () => {
  const selection = tableRef.value.getSelectionRows()
  if (selection.length === 0) {
    ElMessage.warning(t('common.selectRecords'))
    return
  }

  ElMessageBox.confirm(t('common.batchDeleteConfirm', { count: selection.length }), t('common.warning'), {
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selection.map((item: any) => item.TCHR_UUID)
      await axios.delete('/api/teachers/batch', { data: { ids } })
      ElMessage.success(t('common.deleteSuccess'))
      loadTeachers()
    } catch (error) {
      ElMessage.error(t('common.deleteError'))
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await axios.put(`/api/teachers/${form.value.TCHR_UUID}`, form.value)
        } else {
          await axios.post('/api/teachers', form.value)
        }
        
        ElMessage.success(t(isEdit.value ? 'common.editSuccess' : 'common.addSuccess'))
        dialogVisible.value = false
        loadTeachers()
      } catch (error) {
        ElMessage.error(t('common.saveError'))
      }
    }
  })
}

const handleSort = (obj: any) => {
  queryData.value.sortField = obj.prop
  queryData.value.sortOrder = obj.order === 'descending' ? 'desc' : 'asc'
  loadTeachers()
}

const handleSizeChange = (size: number) => {
  queryData.value.pageSize = size
  loadTeachers()
}

const handleCurrentChange = (page: number) => {
  queryData.value.currentPage = page
  loadTeachers()
}

const getTeacherLevelType = (level: number) => {
  switch (level) {
    case 1: return 'info'
    case 2: return 'success'
    case 3: return 'warning'
    default: return 'info'
  }
}

const getTeacherLevelLabel = (level: number) => {
  switch (level) {
    case 1: return t('teacher.level.junior')
    case 2: return t('teacher.level.mid')
    case 3: return t('teacher.level.senior')
    default: return t('teacher.level.unknown')
  }
}

// 初始化
onMounted(() => {
  const dHeight = $(document).height() || 800
  tableHeight.value = dHeight - 25 - 40 - 100
  loadTeachers()
})
</script>

<style scoped>
.teacher-page {
  padding: 20px;
}

header {
  display: flex;
  margin-bottom: 20px;
}

.el-button {
  margin: 2px 0 0 5px;
}

.el-form-item {
  margin-bottom: 0;
}

.label-right-align :deep(.el-form-item__label) {
  text-align: right;
}
</style> 